package com.atguigu.eduService.controller;


import com.atguigu.commonUtils.JwtUtils;
import com.atguigu.commonUtils.Result;
import com.atguigu.commonUtils.ResultEnum;
import com.atguigu.commonUtils.ResultUtil;
import com.atguigu.commonUtils.vo.UcenterMemberVo;
import com.atguigu.eduService.client.UcenterClient;
import com.atguigu.eduService.entity.EduComment;
import com.atguigu.eduService.service.EduCommentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author Chen Wen bo
 * @since 2021-08-19
 */
@Api(tags = "用户评论")
@RestController
@RequestMapping("/eduService/comment")
@CrossOrigin
public class EduCommentController {

    @Resource
    private EduCommentService eduCommentService;
    @Resource
    private UcenterClient ucenterClient;

    @ApiOperation("根据课程id查询评论列表")
    @GetMapping("/getComment/{page}/{limit}")
    public Result<Map<String, Object>> index(@PathVariable Long page, @PathVariable Long limit,String courseId) {
        Page<EduComment> commentPage = new Page<>(page, limit);
        QueryWrapper<EduComment> eduCommentQueryWrapper = new QueryWrapper<>();
        eduCommentQueryWrapper.eq("course_id",courseId);
        eduCommentService.page(commentPage,eduCommentQueryWrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("items", commentPage.getRecords());
        map.put("current", commentPage.getCurrent());
        map.put("pages", commentPage.getPages());
        map.put("size", commentPage.getSize());
        map.put("total", commentPage.getTotal());
        map.put("hasNext", commentPage.hasNext());
        map.put("hasPrevious", commentPage.hasPrevious());
        return ResultUtil.success(map);
    }

    @ApiOperation("添加评论")
    @PostMapping("/addComment")
    public Result<EduComment> addComment(@RequestBody EduComment eduComment, HttpServletRequest request) {
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberId)) {
            return ResultUtil.defineFail(ResultEnum.NOT_LOGIN.code,ResultEnum.NOT_LOGIN.message);
        }
        eduComment.setMemberId(memberId);
        UcenterMemberVo member = ucenterClient.getMember(memberId);
        eduComment.setNickname(member.getNickname());
        eduComment.setAvatar(member.getAvatar());
        eduCommentService.save(eduComment);
        return ResultUtil.success();
    }



}

